package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.DAOs.FriendDAO;
import com.dragonfly.shutter.beans.Friend;
import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.beans.UserDetail;
import com.dragonfly.shutter.services.UserService;
import com.dragonfly.shutter.utils.KeywordFilter;

/**
 * 用户中心控制器
 * @author 黄挺
 *
 */
@Controller
@RequestMapping("/user.html")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private FriendDAO friendDAO;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request, ModelMap model,
			@RequestParam(value="userID", required=false) String userIDStr){
		Integer myID = (Integer) session.getAttribute("userID");
		Message message = null;
		UserDetail user = null;
		
		//未登录的用户
		if( userIDStr == null ){
			message = new Message("您尚未登录请先登录", "请登录", "login.html");
			return new ModelAndView("message", "message", message);
		}
				
		//非法的参数
		if( !KeywordFilter.isNumeric(userIDStr)){
			message = new Message("非法的参数", "操作失败", "login.html");
			return new ModelAndView("message", "message", message);
		}
		
		Integer userID = Integer.parseInt(userIDStr);
		
		//是否为好友
		Friend friend = friendDAO.selectOneFriend(myID, userID);
		
		if( friend != null )
			model.addAttribute("isFriend", true);
		else
			model.addAttribute("isFriend", false);
		
		try {
			user = userService.doService(userID, request.getRequestURL().toString());
		} catch (Exception e) {
			// 不存在的用户或者是未登录的用户
			e.printStackTrace();
			message = new Message(e.getMessage(), "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		
		return new ModelAndView("user", "user", user);
	}
}
